package com.example.demo.util;

import org.springframework.format.annotation.NumberFormat;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;

/**
 * alibaba的
 * @author 陈浩
 * @date 2021/1/9 14:51
 */
public class NumberUtil {

    public NumberUtil() {
    }

    public static Short parseShort(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Short.parseShort(string) : parse(string, declaredField).shortValue();
    }

    public static Long parseLong(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Long.parseLong(string) : parse(string, declaredField).longValue();
    }

    public static Integer parseInteger(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Integer.parseInt(string) : parse(string, declaredField).intValue();
    }

    public static Float parseFloat(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Float.parseFloat(string) : parse(string, declaredField).floatValue();
    }

    public static BigDecimal parseBigDecimal(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? new BigDecimal(string) : BigDecimal.valueOf(parse(string, declaredField).doubleValue());
    }

    public static Byte parseByte(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Byte.parseByte(string) : parse(string, declaredField).byteValue();
    }

    public static Double parseDouble(String string, Field declaredField) throws ParseException {
        return !hasFormat(declaredField) ? Double.parseDouble(string) : parse(string, declaredField).doubleValue();
    }


    private static boolean hasFormat(Field declaredField) {
        NumberFormat annotation = declaredField.getAnnotation(NumberFormat.class);
        return annotation != null && !StringUtils.isEmpty(annotation.pattern());
    }

    private static Number parse(String string, Field declaredField) throws ParseException {
        String format = declaredField.getAnnotation(NumberFormat.class).pattern();
        DecimalFormat decimalFormat = new DecimalFormat(format);
        decimalFormat.setParseBigDecimal(true);
        return decimalFormat.parse(string);
    }

}
